package com.lerning.edu.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.lerning.edu.beans.Student;
import com.lerning.edu.beans.SysUser;
import com.lerning.edu.beans.WorkOrder;
import com.lerning.edu.beans.WorkOrderAuditRecord;
import com.lerning.edu.beans.page.PageList;
import com.lerning.edu.commons.util.DateUtil;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.services.CampusDSRService;
import com.lerning.edu.services.StudentService;
import com.lerning.edu.services.WorkOrderAuditRecordService;
import com.lerning.edu.services.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangwei
 * @since 18/9/3
 */
@Controller
@RequestMapping("/workOrderChangeSchool")
public class WorkOrderChangeSchoolController extends BaseController {
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private WorkOrderAuditRecordService workOrderAuditRecordService;
    @Autowired
    private CampusDSRService campusDSRService;

    @RequestMapping("/apply")
    public String apply(HttpServletRequest request, String employeeId) {

        HttpSession session = request.getSession();

        if(session.getValue(employeeId) != null){
            String value = session.getValue(employeeId).toString();

            if(session.getValue(employeeId) != null && !("").equals(session.getValue(employeeId)) && (employeeId).equals(value)){
                request.setAttribute("isLogin", "N");
            }else{
                request.setAttribute("isLogin", "Y");
            }
        }else {
            request.setAttribute("isLogin", "Y");
        }

        List employees = new ArrayList();
        Map employee = new HashMap();

        if (StringUtil.isEmpty(employeeId)) {
            SysUser user = UserUtils.getUser();
            String account = user.getAccount();
            employees = workOrderService.queryEmployeeByCfield(account);
        } else {
            employees = workOrderService.queryEmployeeByUserID(employeeId);
        }

        if (employees.size() > 0) {
            employee = (HashMap)employees.get(0);
           if (!employee.get("cValue").equals("OA_OAS")) {
               return "/WorkOrderChangeSchool/view";
            }
        } else {
            return "/WorkOrderChangeSchool/view";
        }
        request.setAttribute("tEmployeeID", employeeId);

        return "/WorkOrderChangeSchool/apply";
    }

    //审核任务
    @RequestMapping("/taskList")
    public String list(HttpServletRequest request, WorkOrder workOrder){
        request.setAttribute("workOrder",workOrder);
        return "/WorkOrderChangeSchool/taskList";
    }
    //审核任务
    @RequestMapping("/asynTaskList")
    @ResponseBody
    public PageList asynTaskList(PageList pageList, WorkOrder workOrder) {
        workOrder.setCstatus(1);
        workOrder.setCtype(4);//转校
        return workOrderService.queryPage(pageList, workOrder);
    }

    //操作任务
    @RequestMapping("/operationTaskList")
    public String operationTaskList(HttpServletRequest request, WorkOrder workOrder){
        request.setAttribute("workOrder",workOrder);
        return "/WorkOrderChangeSchool/operationTaskList";
    }

    //操作任务
    @RequestMapping("/asynOperationTaskList")
    @ResponseBody
    public PageList asynOperationTaskList(PageList pageList, WorkOrder workOrder) {
        workOrder.setCstatus(2);
        workOrder.setCtype(4);//转校
        return workOrderService.queryPage(pageList, workOrder);
    }

    //打印停课工单列表
    @RequestMapping("/printList")
    public String printList(HttpServletRequest request, WorkOrder workOrder){
        request.setAttribute("workOrder",workOrder);
        return "/WorkOrderChangeSchool/printList";
    }

    //打印停课工单列表
    @RequestMapping("/asnyPrintList")
    @ResponseBody
    public PageList asnPrintList(PageList pageList, WorkOrder workOrder) {
        workOrder.setCstatus(4);
        workOrder.setCtype(4);//转校
        return workOrderService.queryPage(pageList, workOrder);
    }

    @RequestMapping("/detail")
    public String detail(HttpServletRequest request, String orderNo, String userID, String flag) {

        String returnValue = "WorkOrderChangeSchool/detail";

        Map map = new HashMap();
        map.put("orderNo", orderNo);
        Map workOrderDetail = workOrderService.queryDetail(map);

        if (workOrderDetail == null) {
            returnValue = "WorkOrderChangeSchool/auditPage";
            workOrderDetail = workOrderService.queryDetail1(map);
        } else if (workOrderDetail.get("cStatus").toString().equals("2")) {
            returnValue = "WorkOrderChangeSchool/operation";
        } else if (workOrderDetail.get("cStatus").toString().equals("4")) {
            returnValue = "WorkOrderChangeSchool/printPage";
        }

        map.put("userID", workOrderDetail.get("cUserID"));
        map.put("userId", workOrderDetail.get("cUserID"));

        Map student = studentService.findStudentOne(map);

        String classID = workOrderDetail.get("cClassID").toString();
        String newClassID = workOrderDetail.get("resumeClassID").toString();

        String[] classIDs = new String[10];
        String[] newClassIDs = new String[10];

        List myClass = new ArrayList();

        if(!StringUtil.isEmpty(classID)){
            classIDs = classID.split(",");
        }

        if(!StringUtil.isEmpty(newClassID)){
            newClassIDs = newClassID.split(",");
        }else{
            newClassIDs = classIDs;
        }

        for (int i = 0; i < classIDs.length; i++) {
            map.put("classID", classIDs[i]);
            map.put("newClassID", newClassIDs[i]);

            Map changeSchoolClass = workOrderService.queryChangeSchoolOfClass(map);
            myClass.add(changeSchoolClass);
        }

        WorkOrderAuditRecord woar = new WorkOrderAuditRecord();
        woar.setCworkorderid(workOrderDetail.get("cID").toString());
        List record = workOrderAuditRecordService.queryList(woar);

        request.setAttribute("workOrderDetail", workOrderDetail);
        request.setAttribute("student", student);
        request.setAttribute("classes", myClass);

        request.setAttribute("record", record);

        request.setAttribute("flag", flag);
        request.setAttribute("userID", userID);

        return returnValue;
    }

    @RequestMapping("/findDepart")
    @ResponseBody
    public JSONObject findDepart(
            @RequestParam(value = "userId", required = false) String userId) {
        Map map = new HashMap();
        map.put("userId", userId);

        Student student = studentService.queryByUserId(userId);
        map.put("CampusID", student.getCcampusid());
        List depart = campusDSRService.queryDepartById(map);
        Map dptMap = (HashMap)depart.get(0);
        List departs = campusDSRService.queryDepartListByWorkOrder(map);//校区

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", departs);
        jsonObject.put("campusID", dptMap.get("cName"));//向上取整

        return jsonObject;
    }

    @RequestMapping("/findClassToPage")
    @ResponseBody
    public JSONObject findClassToPage(
            @RequestParam(value = "classID", required = false) String classID,
            @RequestParam(value = "campusID", required = false) String campusID,
            @RequestParam(value = "newClassID", required = false) String newClassID) {

        String[] classIDs = new String[10];
        String[] newClassIDs = new String[10];

        List cscList = new ArrayList();

        Map map = new HashMap();
        if(!StringUtil.isEmpty(classID)){
            classIDs = classID.split(",");
        }

        if(!StringUtil.isEmpty(newClassID)){
            newClassIDs = newClassID.split(",");
        }

        for (int i = 0; i < classIDs.length; i++) {
            map.put("classID", classIDs[i]);
            map.put("newClassID", newClassIDs[i]);

            Map changeSchoolClass = workOrderService.queryChangeSchoolOfClass(map);
            cscList.add(changeSchoolClass);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", cscList);

        return jsonObject;
    }

    @RequestMapping("/save")
    public String save(HttpServletRequest request,
                       @RequestParam(value = "tEmployeeID", required = false) String tEmployeeID,
                       @RequestParam(value = "userId", required = false)String userId,
                       @RequestParam(value = "classID", required = false) String classID,
                       @RequestParam(value = "creason", required = false) String cReason,
                       @RequestParam(value = "cstopclassdate", required = false) String cStopClassDate,
                       @RequestParam(value = "crecoverydate", required = false) String cRecoveryDate,
                       @RequestParam(value = "cremarks", required = false) String cRemarks,
                       @RequestParam(value = "resumeClassID", required = false)String resumeClassID) {

        WorkOrder workOrder = new WorkOrder();

        if(StringUtil.isEmpty(tEmployeeID)){
            SysUser user = UserUtils.getUser();
            List employees = workOrderService.queryEmployeeByCfield(user.getAccount());

            if (employees.size() > 0) {
                Map employee = (HashMap)employees.get(0);
                tEmployeeID = employee.get("cUserID").toString();
            }else{
                tEmployeeID = "3378BBC1-8313-4023-9D15-5C8C58BD66A6";
            }
        }

        workOrder.setCuserid(userId);
        workOrder.setCcreateuser(tEmployeeID);
        workOrder.setCclassid(classID);
        workOrder.setCstatus(1);
        workOrder.setCtype(4);//转校
        workOrder.setCreason(cReason);
        workOrder.setCstopclassdate(DateUtil.formateStringToDate(cStopClassDate));
        workOrder.setCrecoverydate(DateUtil.formateStringToDate(cRecoveryDate));
        workOrder.setCisoriginal(0);
        workOrder.setCremarks(cRemarks);
        workOrder.setCisprint(2);
        workOrder.setCcreatedate(new Date());
        workOrder.setResumeClassID(resumeClassID);

        Map map = new HashMap();
        map.put("userId", userId);
        Map users = workOrderService.queryByUserId(map);
        workOrder.setCampus(users.get("cName").toString());

        map.put("campus", workOrder.getCampus());
        Map maxOrderNo = workOrderService.queryMaxOrderNo(map);

        String orderNo = DateUtil.getYear().substring(2, 4) + users.get("cAddress").toString();
        if (maxOrderNo == null) {
            workOrder.setCorderno(orderNo + "0001");
        } else {
            String oNo = maxOrderNo.get("cOrderNo").toString();
            workOrder.setCorderno(orderNo + StringUtil.autoGenericCode(oNo.substring(oNo.length() - 4, oNo.length()), 4));
        }

        workOrderService.add(workOrder);

        return "redirect:/workOrderInterrupt/listPage?employeeId="+tEmployeeID;
    }
}
